<template>
  <el-row>
    <el-col :span="22" :offset="1" class="search_box">
      <el-autocomplete
        class="search_input"
        v-model="search"
        :fetch-suggestions="handleFocus"
        :select-when-unmatched="true"
        placeholder="请输入内容，回车搜索"
        @select="handleSelect"
        @keyup.enter.native="handleEnter"
      ></el-autocomplete>
    </el-col>
  </el-row>
</template>

<script>
import isEmpty from "@/utils/isEmpty";
import axios from "@/request";

export default {
  name: "Search",
  data() {
    return {
      search: "",
      roomHistory: [],
    };
  },
  mounted() {
    if (!isEmpty(localStorage.roomHistory)) {
      this.roomHistory = JSON.parse(localStorage.roomHistory);
    }
    window.onbeforeunload = () => {
      localStorage.setItem("roomHistory", JSON.stringify(this.roomHistory));
    };
  },
  methods: {
    // 返回建议的回调
    handleFocus(queryString, callback) {
      queryString = queryString.trim();
      let roomHistory = this.roomHistory;
      // filter过滤，条件筛选
      let result = isEmpty(queryString)
        ? roomHistory
        : roomHistory.filter(
            (item) => item.value.toLowerCase().indexOf(queryString) != -1
          );
      callback(result);
    },
    // 建议被选中时的回调
    handleSelect(queryString) {
      this.upKeyword(queryString.value.trim());
      this.handleSearch(queryString.value.trim());
    },
    // 提升关键字位置
    upKeyword(queryString) {
      if (isEmpty(queryString)) return;
      // 遍历，找下标
      let index = -1;
      for (let i = 0; i < this.roomHistory.length; i++) {
        if (this.roomHistory[i].value == queryString) {
          index = i;
        }
      }
      // 如果存在，那么就删除，这是为了提升位置
      if (index != -1) {
        this.roomHistory.splice(index, 1);
      }
      // 不管之前存不存在，现在都得存到数组头部
      this.roomHistory.unshift({ value: queryString });
    },
    handleSearch(queryString) {
      if (isEmpty(queryString)) {
        return this.$bus.$emit("reloadRoomList");
      }
      axios
        .get("/room/searchRoomListByTitle", {
          params: {
            title: queryString,
          },
        })
        .then((res) => {
          if (res.data.code == 200) {
            if (!res.data.data.length == 0) {
              this.$bus.$emit("fillRoomList", res.data.data);
            } else {
              this.$message.info("没有搜索到与该关键词有关的商品信息");
            }
          }
        })
        .catch((e) => {});
    },
  },
};
</script>

<style scoped>
::-webkit-scrollbar-track {
  display: none;
}

.search_box {
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.search_input {
  width: 100%;
}
</style>